//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends egret.DisplayObjectContainer {

    /**
     * 加载进度界面
     * Process interface loading
     */
    private loadingView: LoadingUI;

    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
    }

    private onAddToStage(event: egret.Event) {
        //设置加载进度界面
        //Config to load process interface
        this.loadingView = new LoadingUI();
        this.stage.addChild(this.loadingView);

        //初始化Resource资源加载库
        //initiate Resource loading library
        RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.loadConfig("resource/default.res.json", "resource/");
    }

    /**
     * 配置文件加载完成,开始预加载preload资源组。
     * configuration file loading is completed, start to pre-load the preload resource group
     */
    private onConfigComplete(event: RES.ResourceEvent): void {
        RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
        RES.loadGroup("preload");
    }

    /**
     * preload资源组加载完成
     * Preload resource group is loaded
     */
    private onResourceLoadComplete(event: RES.ResourceEvent) {
        if (event.groupName == "preload") {
            this.stage.removeChild(this.loadingView);
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
            RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
            this.createGameScene();
        }
    }

    /**
     * 资源组加载出错
     *  The resource group loading failed
     */
    private onItemLoadError(event: RES.ResourceEvent) {
        console.warn("Url:" + event.resItem.url + " has failed to load");
    }

    /**
     * 资源组加载出错
     *  The resource group loading failed
     */
    private onResourceLoadError(event: RES.ResourceEvent) {
        //TODO
        console.warn("Group:" + event.groupName + " has failed to load");
        //忽略加载失败的项目
        //Ignore the loading failed projects
        this.onResourceLoadComplete(event);
    }

    /**
     * preload资源组加载进度
     * Loading process of preload resource group
     */
    private onResourceProgress(event: RES.ResourceEvent) {
        if (event.groupName == "preload") {
            this.loadingView.setProgress(event.itemsLoaded, event.itemsTotal);
        }
    }

    private textfield: egret.TextField;
    private isBegin: boolean = false;

    /**
     * 创建游戏场景
     * Create a game scene
     */
    private createGameScene() {
        var bg: egret.Shape = new egret.Shape();
        bg.graphics.beginFill(0x4f0a11);
        bg.graphics.drawRect(0, 0, this.stage.stageWidth, this.stage.stageHeight);
        bg.graphics.endFill();
        this.addChild(bg);

        let stageW = this.stage.stageWidth;
        let stageH = this.stage.stageHeight;

        let tiger: Pocker = new Pocker(false);
        tiger.x = 130;
        tiger.y = 400;
        const tigerAspectRatio = tiger.height / tiger.width;
        tiger.width = stageW / 4;
        tiger.height = tiger.width * tigerAspectRatio;
        tiger.anchorOffsetX = tiger.width / 2;
        this.addChild(tiger);

        let dragon: Pocker = new Pocker(true);
        dragon.x = 370;
        dragon.y = 400;
        const dragonAspectRatio = dragon.height / dragon.width;
        dragon.width = stageW / 4;
        dragon.height = dragon.width * dragonAspectRatio;
        dragon.anchorOffsetX = dragon.width / 2;
        this.addChild(dragon);

        dragon.x += dragon.width / 2;
        tiger.x += tiger.width / 2;

        const waitTime: number = 10;

        var waitTimer = new egret.Timer(1000, waitTime+1);
        var lotteryTimer = new egret.Timer(1000, 6);
        var showTimer = new egret.Timer(1000, 1);

        let self = this;
        this.stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN, () => {
            if (self.isBegin) {
                return;
            }
            self.isBegin = true;
            egret.Tween.get(dragon).to({ scaleX: .7, scaleY: .7 }, 300, egret.Ease.circIn);
            egret.Tween.get(tiger).to({ scaleX: .7, scaleY: .7 }, 300, egret.Ease.circIn);

            let dragonBtn = new Btn("z_dragon_png", () => {
                // alert("龙");
            });
            let tigerBtn = new Btn("z_tiger_png", () => {
                // alert("虎");
            });
            let heBtn = new Btn("z_he_png", () => {
                // alert("合");
            });

            this.addChild(dragonBtn);
            this.addChild(tigerBtn);
            this.addChild(heBtn);

            const btnDistance = (stageW - dragonBtn.width * 2.1) / 4;  //两个按钮之间的间距
            // const btnY = stageH - 10 - dragonBtn.height;
            const btnY = 670;
            dragonBtn.x = btnDistance;
            dragonBtn.y = btnY;
            dragonBtn.scaleX = .7;
            dragonBtn.scaleY = .7;

            heBtn.x = btnDistance * 2 + heBtn.width * .7;
            heBtn.y = btnY;
            heBtn.scaleX = .7;
            heBtn.scaleY = .7;

            tigerBtn.x = btnDistance * 3 + tigerBtn.width * 1.4;
            tigerBtn.y = btnY;
            tigerBtn.scaleX = .7;
            tigerBtn.scaleY = .7;

            waitTimer.start();
            // fixme: 此处应该移除listener
        }, this);

        var countDown = new egret.TextField();
        countDown.size = 40;
        countDown.x = stageW / 2;
        countDown.y = stageH / 2 - tiger.height / 2;
        countDown.textColor = 0xffffff;
        this.addChild(countDown);
        var countNum = [waitTime, 5];
        waitTimer.addEventListener(egret.TimerEvent.TIMER, () => {
            countDown.text = countNum[0] + "";
            --countNum[0];
        }, this);
        waitTimer.addEventListener(egret.TimerEvent.TIMER_COMPLETE, () => {
            tiger.showBg();
            dragon.showBg();
            tiger.startRotate();
            dragon.startRotate();
            lotteryTimer.reset();
            lotteryTimer.start();
        }, this);
        lotteryTimer.addEventListener(egret.TimerEvent.TIMER, () => {
            countDown.visible = false;
            // countDown.text = countNum[1] + "";
            // --countNum[1];
        }, this);
        lotteryTimer.addEventListener(egret.TimerEvent.TIMER_COMPLETE, () => {
            
            showTimer.reset();
            showTimer.start();
            let tigerNum = Math.ceil(Math.random() * 13);
            let dragonNum = Math.ceil(Math.random() * 13);
            let tigerPattern = Math.ceil(Math.random() * 4);
            let dragonPattern = Math.ceil(Math.random() * 4);
            tiger.showFront(tigerPattern, tigerNum);
            dragon.showFront(dragonPattern, dragonNum);
            tiger.stopRotate();
            dragon.stopRotate();
            countNum[1] = 5;
            countNum[0] = waitTime;

        }, this);
        showTimer.addEventListener(egret.TimerEvent.TIMER_COMPLETE, () => {
            
            // countNum[1] = 5;
            waitTimer.reset();
            waitTimer.start();
            countDown.text = waitTime + "";
            countDown.visible = true;
        }, this);
    }
    /**
     * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
     * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
     */
    private createBitmapByName(name: string) {
        let result = new egret.Bitmap();
        let texture: egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;
    }

    /**
     * 描述文件加载成功，开始播放动画
     * Description file loading is successful, start to play the animation
     */
    private startAnimation(result: string[]) {
        let parser = new egret.HtmlTextParser();

        let textflowArr = result.map(text => parser.parse(text));
        let textfield = this.textfield;
        let count = -1;
        let change = () => {
            count++;
            if (count >= textflowArr.length) {
                count = 0;
            }
            let textFlow = textflowArr[count];

            // 切换描述内容
            // Switch to described content
            textfield.textFlow = textFlow;
            let tw = egret.Tween.get(textfield);
            tw.to({ "alpha": 1 }, 200);
            tw.wait(2000);
            tw.to({ "alpha": 0 }, 200);
            tw.call(change, this);
        };

        change();
    }
}


